<template>
  <div class="main-content">
    <div class="row">
      <div class="col-sm-4 col-md-3">
        <ul class="template-title-fl">
          <li>
            <button type="button"
                    class="btn btn-default btn-theme addBtn"
                    v-on:click="openCooDeptModal('A')"
                    v-res="{code:'menu_0003_0003_0001'}">新增</button>
          </li>
          <li>
            <button type="button"
                    class="btn btn-default btn-theme"
                    v-on:click="openCooDeptModal('U')"
                    v-res="{code:'menu_0003_0003_0002'}">修改</button>
          </li>
          <li>
            <button type="button"
                    class="btn btn-default btn-theme"
                    v-on:click="delDept"
                    v-res="{code:'menu_0003_0003_0003'}">删除</button>
          </li>
          <li>
            <button type="button"
                    class="btn btn-default btn-theme"
                    v-on:click="uploadExcel()"
                    v-res="{code:'menu_0003_0003_0004'}">导入合作机构</button>
          </li>
          <li>
            <button type="button"
                    class="btn btn-default btn-theme"
                    v-on:click="mergeCooModal(0)"
                    v-res="{code:'menu_0003_0003_00041'}">合并</button>
          </li>
          <li>
            <button type="button"
                    class="btn btn-default btn-theme"
                    v-on:click="mergeCooModal(1)"
                    v-res="{code:'menu_0003_0003_00042'}">转移</button>
          </li>
        </ul>
        <div class="table-filter"
             style="overflow-y: auto;height: 450px;">
          <ul class="template-title-fls"
              style="padding: 10px 0 0 10px;">
            <li>
              <input type="text"
                     v-model="searchDeptModel.deptName"
                     id="key"
                     class="form-control-sm"
                     style="width:100%;"
                     placeholder="请输入机构名称、渠道经理名" />
            </li>
            <li>
              <button type="button"
                      class="btn btn-default btn-theme"
                      v-on:click="queryDetpByDeptName()">查询</button>
            </li>
          </ul>
          <ul id="orgTree"
              class="ztree"></ul>
          <span id="orgTreeText"
                style="padding-left: 10px;font-weight: bolder;display: none;">无查询结果</span>
        </div>
      </div>
      <div class="col-sm-8 col-md-9">
        <form id="searchForm">
          <ul class="template-title-fls">
            <li>
              <input type="text"
                     v-model="searchUserModel.departmentName"
                     name="accountName"
                     class="form-control-sm"
                     placeholder="机构名称" />
            </li>
            <li>
              <input type="text"
                     v-model="searchUserModel.accountName"
                     name="accountName"
                     class="form-control-sm"
                     placeholder="经纪人姓名" />
            </li>
            <li>
              <input type="text"
                     v-model="searchUserModel.phone"
                     class="form-control-sm"
                     placeholder="手机号码" />
            </li>
            <li>
              <select class="form-control-sm"
                      style="float:left"
                      v-model="searchUserModel.accountType">
                <option value>是否为超管</option>
                <option value="0">是</option>
                <option value="1">否</option>
              </select>
            </li>
            <li>
              <button type="button"
                      class="btn btn-default btn-theme"
                      v-on:click="loadPartnerByDept()">查询</button>
            </li>
            <li>
              <button type="button"
                      class="btn btn-default btn-theme addBtn2"
                      v-on:click="openCooUserModal('A', '')"
                      v-res="{code:'menu_0003_0003_0005'}">新增</button>
            </li>
            <li>
              <button type="button"
                      class="btn btn-default btn-theme"
                      v-if="exportBtnShow"
                      v-on:click="exportCooUser()"
                      v-res="{code:'menu_0003_0003_0009'}">导出</button>
            </li>
            <li>
              <button type="button"
                      class="btn btn-default btn-theme"
                      v-if="!exportBtnShow"
                      v-on:click="exportRepeatMsg()"
                      v-res="{code:'menu_0003_0003_0009'}"
                      style="background-color: #999;">导出{{ timeOut }}</button>
            </li>
            <li>
              <button type="button"
                      class="btn btn-default btn-theme"
                      v-on:click="showQrCode()"
                      v-res="{code:'menu_0003_0001_0012'}">生成当前机构注册二维码</button>
            </li>
            <li>
              <button type="button"
                      class="btn btn-default btn-theme-border"
                      v-if="(btnFlg && registerStatus == '0')"
                      v-on:click="registerStatusClick()">启用当前机构注册</button>
            </li>
            <li>
              <button type="button"
                      class="btn btn-default btn-theme-cancel"
                      v-if="(btnFlg && registerStatus == '1')"
                      v-on:click="registerStatusClick()">暂停当前机构注册</button>
            </li>
          </ul>
        </form>
        <div class="table-responsive">
          <table class="table table-striped table-bordered min-width-790">
            <thead>
              <tr>
                <th width="5%">序号</th>
                <th width="8%">公司代码</th>
                <th width="8%">公司名称</th>
                <th width="15%">部门</th>
                <th width="8%">员工姓名</th>
                <th width="10%">联系电话</th>
                <th width="8%">角色</th>
                <th width="5%">状态</th>
                <th width="8%">管理员</th>
                <th width="10%">渠道经理</th>
                <th width="28%">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(row, index) in rows">
                <td>{{index + 1}}</td>
                <td>{{row.companyCode}}</td>
                <td>{{row.companyName}}</td>
                <td v-if="row.storeName && row.storeName != row.departmentName">{{row.storeName}}-{{row.departmentName}}</td>
                <td v-else>{{row.departmentName}}</td>
                <td>{{row.accountName}}</td>
                <td>{{row.phone}}</td>
                <td v-if="row.accountType == 0"
                    style="color: red;">超级管理员</td>
                <td v-else>{{ row.roleName }}</td>
                <td>
                  <span :class="[{stateOne: row.status==1, stateTwo: row.status==0}]">{{row.status==1?"启用":"禁用"}}</span>
                </td>
                <td>{{row.accountType==1?"否":"是"}}</td>
                <td>{{row.principalName}}</td>
                <td>
                  <button type="button"
                          class="btnA edit"
                          v-show="loginInfo.accountType == 0 && row.accountType == 0"
                          v-on:click="openCooUserModal('U', row.id)"
                          v-res="{code:'menu_0003_0003_0006'}">编辑</button>
                  <button type="button"
                          class="btnA delete-btn"
                          v-show="loginInfo.accountType == 0 && row.accountType == 0"
                          v-on:click="forbiddenOrNotPartner(row.id, row.status)"
                          v-res="{code:'menu_0003_0003_0008'}">{{row.status==1?"禁用":"启用"}}</button>
                  <button type="button"
                          class="btnA delete-btn"
                          v-show="loginInfo.accountType == 0 && row.accountType == 0"
                          v-on:click="delPartner(row.id);"
                          v-res="{code:'menu_0003_0003_0007'}">删除</button>
                  <button type="button"
                          class="btnA delete-btn"
                          v-show="row.accountType != 0"
                          v-on:click="openCooUserModal('V', row.id);"
                          v-res="{code:'menu_0003_0003_0010'}">查看</button>
                  <!-- <button v-if="row.accountType == 0"
                          type="button"
                          class="btnA delete-btn"
                          v-on:click="chooseUserClick(row)">变更管理员</button> -->
                  <button v-if="row.accountType == 1"
                          type="button"
                          class="btnA delete-btn"
                          v-res="{code:'menu_0003_0003_0012'}"
                          v-on:click="setAccountType(row, 1)">设为管理员</button>
                  <button v-if="row.accountType == 0"
                          type="button"
                          class="btnA delete-btn"
                          v-res="{code:'menu_0003_0003_0013'}"
                          v-on:click="setAccountType(row, 0)">取消管理员</button>
                  <button type="button"
                          class="btnA delete-btn"
                          v-res="{code:'menu_0003_0003_0014'}"
                          v-on:click="openChangePartnerDept(row)">调整部门</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div id="laypage_coo_dept"></div>
      </div>
    </div>
    <cooDeptModal v-bind:cooDeptInfo="cooDeptInfo"
                  :modalId="modalId"
                  v-on:cooDeptListener="cooDeptReturn"></cooDeptModal>
    <cooUserModal v-bind:cooUserInfo="cooUserInfo"
                  v-on:cooUserListener="cooUserReturn"></cooUserModal>
    <userChangeDeptModal v-bind:partnerModal="partnerInfo"
                         v-on:selfUserListener='selfUserReturn'></userChangeDeptModal>
    <mergeCooDeptModal v-bind:mergeDeptModal="acceptDept"
                       v-on:saveOrgListener='saveOrgReturn'
                       ref="mdm"></mergeCooDeptModal>
    <changeCooDeptModal v-bind:mergeDeptModal="acceptDept"
                        v-on:saveOrgListener='saveOrgReturn'
                        ref="cdm"></changeCooDeptModal>
    <uploadExcelModal v-on:saveExcelListener="saveOrgReturn"></uploadExcelModal>
    <QRCode v-bind:qrcode="qrcodeNode"
            ref="qrCode"></QRCode>
    <Modal v-model="changeManagerConfirmVisible"
           @on-ok="changeManager"
           @on-cancel="cancelManagerConfirm">
      <div>
        <p style="font-size: 30px;  font-weight: 700;  color: #f98e68;">请确认!</p>

        <p style="font-size: 16px;"
           v-if="setAdminDisplayFlag">
          是否确认将
          <span style="color: #f98e68;">{{managerInfo.name}}</span>
          设置为管理员。
        </p>
        <p style="font-size: 16px;"
           v-if="cancelAdminDisplayFlag">
          是否确认将
          <span style="color: #f98e68;">{{managerInfo.name}}</span>
          取消管理员权限。取消后将失去管理员所有权限
        </p>
      </div>
    </Modal>

    <!-- 变更管理员 -->
  </div>
</template>

<script>
import cooDeptModal from "./cooDeptModal.vue";
import cooUserModal from "./cooUserModal.vue";
import bindPremisesModal from "./bindPremisesModal.vue";
import uploadExcelModal from "./uploadExcel.vue";
import ztreeCore from "../../assets/js/zTree/jquery.ztree.core-3.5.min.js";
import ztreeAll from "../../assets/js/zTree/jquery.ztree.all.min.js";
import ztreeHide from "../../assets/js/zTree/jquery.ztree.exhide.js";
import mergeCooDeptModal from "./mergeCooDept.vue";
import changeCooDeptModal from "./changeCooDept.vue";
import QRCode from "../common/QRCode.vue";
// import ChangeManagerModal from './changeManagerModal.vue'
import { Utils, Service } from "../../js/base";
import userChangeDeptModal from "./userChangeDept.vue";

export default {
  data() {
    return {
      isOnly: true,
      // changeManagerVisible: false, // 修改管理员
      changeManagerConfirmVisible: false, // 二次确认
      setAdminDisplayFlag: false,
      cancelAdminDisplayFlag: false,
      managerInfo: {
        name: "",
        id: ""
      },
      //managerList: [],
      loginInfo: {
        userId: window.localStorage.getItem("1_userId"),
        isLogin: window.localStorage.getItem("1_isLogin"),
        accountType: window.localStorage.getItem("1_accountType")
      },
      orgTreeData: [],
      rows: [],
      pageInfo: {
        pageNo: 1,
        pageSize: 10
      },
      addUserShow: false,
      addOrgShow: false,
      searchUserModel: {
        departmentName: "",
        accountName: "",
        phone: "",
        accountType: ""
      },
      cooDeptInfo: {
        orgId: "",
        parentOrgId: "",
        optType: "",
        nodeLevel: ""
      },
      cooUserInfo: {
        partnerId: "",
        orgId: "",
        optType: ""
      },
      forbiddenOrNotInfo: {
        id: "",
        status: ""
      },
      bindPremisesInfo: {
        partnerId: "",
        partnerName: ""
      },
      partnerInfo: {
        id: "",
        name: ""
      },
      searchDeptModel: {
        deptName: ""
      },
      hiddenNodes: [],
      nodeList: [],
      qrcodeShow: false,
      qrcodeNode: {},
      exportBtnShow: true,
      btnFlg: false,
      registerStatus: 0,
      agentCompanyId: "",
      timeOut: 10,
      // tableData: [],
      deptIds: "", // 选中的树结构deptIds
      merchantId: "", // 选中的树结构的merchantId
      acceptDept: {
        id: "",
        name: "",
        level: ""
      },
      modalId: null
    };
  },
  components: {
    uploadExcelModal,
    cooDeptModal,
    cooUserModal,
    QRCode,
    userChangeDeptModal,
    mergeCooDeptModal,
    changeCooDeptModal
  },
  mounted: function () {
    this.loadOrgTreeData();
    this.getCompanyModalId();
  },
  methods: {
    // 获取总代公司的自定义模板id
    getCompanyModalId() {
      let url = this.utilHelper.apiUrl + "/api/getModelByNameAndType";
      this.$http
        .post(url, { params: { modelName: "营业执照", type: "1" } })
        .then(
          (response) => {
            if (
              response.body.result === "1" &&
              response.body.resData.modelList
            ) {
              this.modalId = response.body.resData.modelList[0].id;
            }
          },
          (response) => {}
        );
    },
    //部门合并弹框
    mergeCooModal: function (optType) {
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      var nodes = treeObj.getSelectedNodes();
      if (nodes.length == 0) {
        layer.msg("请选择部门");
        return;
      }
      if (nodes[0].level == 0) {
        layer.msg("顶级部门不能修改");
        return;
      }
      var setting = {
        data: {
          simpleData: {
            enable: true
          }
        }
      };
      if (0 == optType) {
        this.acceptDept.id = nodes[0].id;
        this.acceptDept.name = nodes[0].name;
        this.acceptDept.level = nodes[0].level;

        if (treeObj) {
          var treeNodes = [];
          for (var i = 0; i < treeObj.getNodes().length; i++) {
            if (treeObj.getNodes()[i].merchantId == nodes[0].merchantId) {
              treeNodes.push(treeObj.getNodes()[i]);
              break;
            }
          }
          $.fn.zTree.init($("#acceptTree"), setting, treeNodes);
        }
        $("#mergeCooDeptModal").modal("show");
      } else if (1 == optType) {
        this.acceptDept.id = nodes[0].id;
        this.acceptDept.name = nodes[0].name;
        this.acceptDept.level = nodes[0].level;
        if (treeObj) {
          var treeNodes = [];
          for (var i = 0; i < treeObj.getNodes().length; i++) {
            if (treeObj.getNodes()[i].merchantId == nodes[0].merchantId) {
              treeNodes.push(treeObj.getNodes()[i]);
              break;
            }
          }
          this.removeChildren(treeNodes, this.acceptDept.id);
          $.fn.zTree.init($("#changeTree"), setting, treeNodes);
        }
        $("#changeCooDeptModal").modal("show");
      }
    },
    /**
     * 移除子节点和当前ID一致的子节点
     */
    removeChildren(treeNodes, id) {
      if (!treeNodes) {
        return;
      }
      for (var i = 0; i < treeNodes.length; i++) {
        while (treeNodes[i].id == id) {
          treeNodes.splice(i, 1);
          return;
        }
        this.removeChildren(treeNodes[i].children, id);
      }
    },
    /**
     * 设置用户类型
     */
    setAccountType(info, accountType) {
      // this.changeManagerVisible = true;
      this.managerInfo.id = info.id; //
      this.managerInfo.name = info.accountName; //info.accountName //
      if (accountType == 1) {
        this.setAdminDisplayFlag = true;
        this.cancelAdminDisplayFlag = false;
      } else if (accountType == 0) {
        this.setAdminDisplayFlag = false;
        this.cancelAdminDisplayFlag = true;
      }
      this.changeManagerConfirmVisible = true;
    },
    /**
     * 调整部门
     */
    openChangePartnerDept: function (row) {
      console.log(row);
      var setting = {
        data: {
          simpleData: {
            enable: true
          }
        }
      };
      var _self = this;
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      this.partnerInfo.id = row.id;
      this.partnerInfo.name = row.accountName;
      if (treeObj) {
        var treeNodes = [];
        console.log(treeObj.getNodes());
        for (var i = 0; i < treeObj.getNodes().length; i++) {
          if (treeObj.getNodes()[i].merchantId == row.higherid) {
            treeNodes.push(treeObj.getNodes()[i]);
            break;
          }
        }
        $.fn.zTree.init($("#partnerTree"), setting, treeNodes);
      }
      $("#changePartnerDeptModal").modal("show");
    },
    selfUserReturn() {
      this.loadPartnerByDept(true);
    },
    /**
     * 显示二次确认框
     */
    showChangeManagerConfirm() {
      // this.changeManagerConfirmVisible = true;
      // this.changeManagerVisible = false;
      this.managerInfo.id = selected[0].id; //
      this.managerInfo.name = selected[0].accountName; //
    },
    /**
     * 修改管理员
     */
    changeManager(accountType) {
      let _this = this;
      var body = {};
      body.params = {
        id: _this.managerInfo.id,
        accountType: _this.setAdminDisplayFlag ? 0 : 1
      };
      let url = _this.utilHelper.apiUrl + "/api/agent/updateAccountType";
      _this.$http.post(url, body).then(
        (response) => {
          layer.msg("修改成功", {
            time: 1000
          });
          _this.loadPartnerByDept(true);
        },
        (response) => {}
      );
    },
    cancelManagerConfirm() {
      this.changeManagerConfirmVisible = false;
    },
    loadOrgTreeData: function () {
      var _self = this;
      //ztree基础属性设置
      var setting = {
        data: {
          simpleData: {
            enable: true
          }
        },
        callback: {
          onClick: _self.zreeOnClick,
          beforeClick: _self.zreeBeforeClick
        }
      };
      var body = {};
      body.params = {};
      var url = _self.utilHelper.apiUrl + "/api/getAgentOrgTree";
      _self.$http.post(url, body).then(
        (response) => {
          var resData = response.body.resData;
          var nodesList = resData.nodesList;
          var result = resData.result;
          $.fn.zTree.init($("#orgTree"), setting, nodesList);
          //机构树加载成功后,加载经纪人数据
          _self.loadPartnerByDept();
        },
        (response) => {}
      );
    },
    zreeOnClick: function (event, treeId, treeNode, clickFlag) {
      this.loadPartnerByDept();
    },
    zreeBeforeClick: function (treeId, treeNode, clickFlag) {
      var _self = this;
      if (treeNode) {
        if ($("#" + treeNode.tId + "_a").hasClass("curSelectedNode")) {
          $("#" + treeNode.tId + "_a").removeClass("curSelectedNode");
          var treeObj = $.fn.zTree.getZTreeObj("orgTree");
          treeObj.cancelSelectedNode();
          _self.loadPartnerByDept();
          return false;
        }
      }
    },
    openCooDeptModal(optType) {
      var _self = this;
      _self.cooDeptInfo = {};
      //获取选中的树节点
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      var allNodes = treeObj.getNodes();
      var nodes = treeObj.getSelectedNodes();
      var nodeLevel = 1;
      if (nodes.length > 0) {
        var parentNode = nodes[0].getParentNode();
        nodeLevel = 2;
        if (parentNode) {
          parentNode = parentNode.getParentNode();
          nodeLevel = 3;
          if (parentNode) {
            nodeLevel = 4;
          }
        }
      }
      _self.cooDeptInfo.nodeLevel = nodeLevel;
      _self.cooDeptInfo.optType = optType;
      _self.cooDeptInfo.orgId = "";
      _self.cooDeptInfo.parentOrgId = "";
      if ("A" == optType) {
        // if (nodeLevel > 3) {
        //   layer.msg("合作机构,只支持三级!", {
        //     time: 1000
        //   });
        // } else {
        //得到第一个选中的节点（此处位单节点选中，因此直接获取即可）
        var selNode = nodes[0];

        if (selNode) {
          _self.cooDeptInfo.parentOrgId = selNode.id;
        }
        $("#cooDeptModal").modal("show");
        // }
      } else if ("U" == optType) {
        _self.cooDeptInfo.nodeLevel = nodeLevel - 1;
        if (allNodes.length > 0 && nodes.length > 0) {
          var selNode = nodes[0];
          _self.cooDeptInfo.orgId = selNode.id;
          _self.cooDeptInfo.merchantId = selNode.merchantId;
          _self.cooDeptInfo.pId = selNode.pId;
          $("#cooDeptModal").modal("show");
        } else {
          //未选中任何部门，提示用户选择
          layer.msg("请选择一个部门 ", {
            time: 1000
          });
        }
      }
    },
    cooDeptReturn() {
      this.loadOrgTreeData();
    },
    registerStatusClick: function () {
      var _self = this;
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      var params = {};
      if (treeObj) {
        var btnMsg = "启用";
        if (_self.registerStatus == "1") {
          btnMsg = "暂停";
        }
        params["companyId"] = _self.agentCompanyId;
        params["ifRegisterFlg"] = _self.registerStatus;
        layer.confirm(
          "是否确认" + btnMsg + "当前机构注册？",
          {
            btn: ["是", "否"] //按钮
          },
          function () {
            var body = {};
            body.params = params;
            var url = _self.utilHelper.apiUrl + "/api/agentRegisterSwitch";
            _self.$http.post(url, body).then(
              (response) => {
                var resData = response.body.resData;
                var result = resData.result;
                var resultMsg = resData.resultMsg;
                //输出操作信息
                if ("1" == result) {
                  layer.msg(btnMsg + "成功", {
                    time: 1000
                  });
                  _self.loadOrgTreeData();
                } else {
                  layer.msg(btnMsg + "失败", {
                    time: 1000
                  });
                }
              },
              (response) => {}
            );
          },
          function () {}
        );
      }
    },
    delDept: function () {
      var _self = this;
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      var nodes = treeObj.getSelectedNodes();
      if (nodes.length > 0) {
        //得到第一个选中的节点（此处位单节点选中，因此直接获取即可）
        var selNode = nodes[0];
        var id = selNode.id;
        var params = {};
        params["id"] = id;
        layer.confirm(
          "您是否要删除该机构？",
          {
            btn: ["确定删除", "再考虑考虑"] //按钮
          },
          function () {
            var body = {};
            body.params = params;
            var url = _self.utilHelper.apiUrl + "/api/delDept";
            _self.$http.post(url, body).then(
              (response) => {
                var resData = response.body.resData;
                var result = resData.result;
                var resultMsg = resData.resultMsg;
                //输出操作信息
                layer.msg(
                  resultMsg,
                  {
                    time: 1000
                  },
                  function () {
                    if ("1" == result) {
                      _self.loadOrgTreeData();
                    }
                  }
                );
              },
              (response) => {}
            );
          },
          function () {}
        );
      } else {
        //未选中任何部门，提示用户选择
        layer.msg("请选择一个要删除的部门", {
          time: 1000
        });
      }
    },
    loadPartnerByDept: function (obj) {
      //根据机构信息，获取用户
      var _self = this;
      var params = {};
      if (!obj) {
        _self.pageInfo.pageNo = 1;
        _self.pageInfo.pageSize = 10;
      }
      params["pageNo"] = _self.pageInfo.pageNo;
      params["pageSize"] = _self.pageInfo.pageSize;
      params["departmentName"] = _self.searchUserModel.departmentName;
      params["accountName"] = _self.searchUserModel.accountName;
      params["phone"] = _self.searchUserModel.phone;
      params["accountType"] = _self.searchUserModel.accountType;
      params["userId"] = _self.loginInfo.userId;
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      if (treeObj) {
        var node = treeObj.getSelectedNodes();
        // console.log('node=====', node);
        var nodes = "";
        if (node.length > 0) {
          this.merchantId = node[0].merchantId;
          var childNodes = treeObj.transformToArray(node);
          for (var i = 0; i < childNodes.length; i++) {
            nodes += parseInt(childNodes[i].id) + ",";
          }
          //获取机构门店组别
          _self.getQRCodeInfoByNode(node[0]);
        } else {
          var firstNodes = treeObj.getNodes();
          var allNodes = treeObj.transformToArray(firstNodes);
          for (var i = 0; i < allNodes.length; i++) {
            nodes += parseInt(allNodes[i].id) + ",";
          }
          _self.qrcodeNode = {};
          this.merchantId = "";
        }
        params["deptIds"] = nodes.substring(0, nodes.lastIndexOf(","));
        this.deptIds = nodes.substring(0, nodes.lastIndexOf(","));
      }
      var body = {};
      body.params = params;
      var url = this.utilHelper.apiUrl + "/api/getAgentPartnerPage";
      this.$http.post(url, body).then(
        (response) => {
          var resData = response.body.resData;
          var total = resData.page.total;
          var totalPages = resData.page.totalPages;
          var rows = resData.page.rows;
          var btnFlg = resData.btnFlg;
          var registerStatus = "0";
          if (btnFlg) {
            registerStatus = resData.registerStatus;
          }
          _self.agentCompanyId = resData.agentCompanyId;
          _self.rows = rows;
          _self.btnFlg = btnFlg;
          _self.registerStatus = registerStatus;
          //加载分页组件
          layui.laypage.render({
            elem: $("#laypage_coo_dept"), //容器。值支持id名、原生dom对象，jquery对象,
            limit: _self.pageInfo.pageSize,
            curr: _self.pageInfo.pageNo,
            count: total,
            theme: "#f87242;", //皮肤
            first: "首页", //若不显示，设置false即可
            last: "尾页", //若不显示，设置false即可
            prev: "上一页", //若不显示，设置false即可
            next: "下一页", //若不显示，设置false即可
            layout: ["prev", "page", "next", "skip", "count"],
            jump: function (obj, first) {
              if (!first) {
                _self.pageInfo.pageNo = obj.curr;
                _self.loadPartnerByDept(true);
              }
            }
          });
        },
        (response) => {
          layer.msg("加载会员失败!", {
            time: 1000
          });
        }
      );
    },
    openCooUserModal(optType, partnerId) {
      //获取选中的树节点
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      var allNodes = treeObj.getNodes();
      var nodes = treeObj.getSelectedNodes();
      if ("A" == optType) {
        //新增需要机构节点
        if (nodes.length > 0) {
          //得到第一个选中的节点（此处位单节点选中，因此直接获取即可）
          var selNode = nodes[0];
          this.cooUserInfo.orgId = selNode.id;
          this.cooUserInfo.optType = optType;
          $("#cooUserModal").modal("show");
        } else {
          //未选中任何部门，提示用户选择
          layer.msg("请选择一个部门 ", {
            time: 1000
          });
        }
      } else if ("U" == optType || "V" == optType) {
        //修改无需机构节点，需得到会员ID
        this.cooUserInfo.partnerId = partnerId;
        this.cooUserInfo.optType = optType;
        $("#cooUserModal").modal("show");
      }
    },
    cooUserReturn() {
      this.loadPartnerByDept(true);
    },
    forbiddenOrNotPartner(partnerId, status) {
      //0: 禁用 1: 启用
      //禁用变启用,启用变禁用
      var _self = this;
      var operationMsg = "禁用";
      if (status == 0) {
        operationMsg = "启用";
      }
      layer.confirm(
        "您是否要" + operationMsg + "该人员？",
        {
          btn: ["确定" + operationMsg, "再考虑考虑"] //按钮
        },
        function () {
          _self.forbiddenOrNotInfo.id = partnerId;
          _self.forbiddenOrNotInfo.status = status;
          var params = _self.forbiddenOrNotInfo;
          var body = {};
          body.params = params;
          var url = _self.utilHelper.apiUrl + "/api/forbiddenOrNotPartner";
          _self.$http.post(url, body).then(
            (response) => {
              var resData = response.body.resData;
              var result = resData.result;
              var resultMsg = resData.resultMsg;
              //输出操作信息
              layer.msg(
                resultMsg,
                {
                  time: 1000
                },
                function () {
                  if ("1" == result) {
                    _self.loadPartnerByDept(true);
                  }
                }
              );
            },
            (response) => {}
          );
        },
        function () {}
      );
    },
    delPartner(partnerId) {
      //0: 禁用 1: 启用
      //禁用变启用,启用变禁用
      var _self = this;
      layer.confirm(
        "您是否要删除该人员？",
        {
          btn: ["确定删除", "再考虑考虑"] //按钮
        },
        function () {
          var params = { id: partnerId };
          var body = {};
          body.params = params;
          var url = _self.utilHelper.apiUrl + "/api/delPartner";
          _self.$http.post(url, body).then(
            (response) => {
              var resData = response.body.resData;
              var result = resData.result;
              var resultMsg = resData.resultMsg;
              //输出操作信息
              layer.msg(
                resultMsg,
                {
                  time: 1000
                },
                function () {
                  if ("1" == result) {
                    _self.loadPartnerByDept(true);
                  }
                }
              );
            },
            (response) => {}
          );
        },
        function () {}
      );
    },
    exportCooUser() {
      if (this.rows.length <= 0) {
        layer.msg("当前数据为空，无法导出");
        return false;
      }
      var _self = this;
      _self.exportBtnShow = false;
      var params = {};
      params["departmentName"] = _self.searchUserModel.departmentName;
      params["accountName"] = _self.searchUserModel.accountName;
      params["phone"] = _self.searchUserModel.phone;
      params["accountType"] = _self.searchUserModel.accountType;
      params["userId"] = window.localStorage.getItem("1_userId");
      params["deptId"] = "";
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      if (treeObj) {
        var node = treeObj.getSelectedNodes();
        if (node.length > 0) {
          params["deptId"] = node[0].id;
        }
      }
      var url =
        _self.utilHelper.apiUrl +
        "/api/exportPartner?params.userId=" +
        params.userId +
        "&params.accountName=" +
        params.accountName +
        "&params.phone=" +
        params.phone +
        "&params.accountType=" +
        params.accountType +
        "&params.departmentName=" +
        params.departmentName +
        "&params.deptId=" +
        params.deptId +
        "&params.loginType=1";
      window.location.href = url;

      var exportInterval = setInterval(function () {
        if (_self.timeOut <= 0) {
          window.clearInterval(exportInterval);
          _self.timeOut = 10;
          _self.exportBtnShow = true;
        } else {
          _self.timeOut -= 1;
        }
      }, 1000);
    },
    exportRepeatMsg: function () {
      var _self = this;
      layer.msg(_self.timeOut + "秒后可再次导出,请稍等片刻!");
      return;
    },
    queryDetpByDeptName: function () {
      var _self = this;
      var node_type = "name";
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      var allNode = treeObj.transformToArray(treeObj.getNodes());
      treeObj.hideNodes(allNode);

      var keywords = _self.searchDeptModel.deptName;
      if (keywords == "") {
        $("#orgTreeText").hide();
        treeObj.showNodes(allNode);
        treeObj.expandAll(false);
      } else {
        //_self.nodeList = treeObj.getNodesByParamFuzzy("text", keywords, null);
        _self.nodeList = treeObj.getNodesByFilter(_self.filterFunc);
        _self.nodeList = treeObj.transformToArray(_self.nodeList);
        for (var n in _self.nodeList) {
          if (_self.nodeList.hasOwnProperty(n)) {
            _self.findParent(treeObj, _self.nodeList[n]);
          }
        }
        if (_self.nodeList.length > 0) {
          $("#orgTreeText").hide();
          treeObj.showNodes(_self.nodeList);
        } else {
          $("#orgTreeText").show();
        }
      }
    },
    filterFunc: function (node) {
      var _self = this;
      var keywords = _self.searchDeptModel.deptName;
      if (node.name.indexOf(keywords) !== -1) return true;
      if (node.other && node.other.indexOf(keywords) !== -1) return true;
      return false;
    },
    findParent: function (treeObj, node) {
      var _self = this;
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      treeObj.expandNode(node, true, false, false);
      var pNode = node.getParentNode();
      if (pNode != null) {
        _self.nodeList.push(pNode);
        _self.findParent(treeObj, pNode);
      }
    },
    saveOrgReturn() {
      this.loadOrgTreeData();
    },
    uploadExcel: function () {
      $("#uploadExcelModal").modal("show");
    },
    showQrCode() {
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      var allNodes = treeObj.getNodes();
      var nodes = treeObj.getSelectedNodes();
      if (nodes.length == 0) {
        layer.msg("请选择一个部门 ", {
          time: 1000
        });
        return;
      } else {
        //获取数据，机构，门店，组别
        $("#qrCode").show();
        // 生成小程序码
        this.$refs.qrCode.wxqrcode();
      }
    },
    getQRCodeInfoByNode(node) {
      if (node.level == 0) {
        this.qrcodeNode.orgName = node.name;
        this.qrcodeNode.orgId = node.merchantId;
        this.qrcodeNode.qrCodeId = node.id;
        this.qrcodeNode.storeName = "";
        this.qrcodeNode.storeId = "";
        this.qrcodeNode.groupName = "";
        this.qrcodeNode.groupId = "";
      }
      if (node.level == 1) {
        this.qrcodeNode.storeName = node.name;
        this.qrcodeNode.storeId = node.id;
        this.qrcodeNode.qrCodeId = node.id;
        let pnode = node.getParentNode();
        if (pnode) {
          this.qrcodeNode.orgName = pnode.name;
          this.qrcodeNode.orgId = pnode.merchantId;
        }
        this.qrcodeNode.groupName = "";
        this.qrcodeNode.groupId = "";
      }
      if (node.level == 2) {
        this.qrcodeNode.groupName = node.name;
        this.qrcodeNode.groupId = node.id;
        this.qrcodeNode.qrCodeId = node.id;
        let snode = node.getParentNode();
        if (snode) {
          this.qrcodeNode.storeName = snode.name;
          this.qrcodeNode.storeId = snode.id;
          let pnode = snode.getParentNode();
          if (pnode) {
            this.qrcodeNode.orgName = pnode.name;
            this.qrcodeNode.orgId = pnode.merchantId;
          }
        }
      }
    }
  }
};
</script>
<style>
.btn-theme-cancel {
  background-color: #f87242;
  color: #fff;
  padding: 3px 11px;
}
.btn-theme-cancel {
  background-color: #fff;
  color: #949494;
  border: 1px solid #949494;
}
.btn-theme-cancel:hover,
.btn-theme-cancel:focus {
  color: #949494;
  background-color: #f1f1f1;
}
</style>
